package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"os"

	"github.com/xuri/excelize/v2"
)

func main() {
	var inputfile string
	var outputfile string
	flag.StringVar(&inputfile, "i", "", "输入excel文件")
	flag.StringVar(&outputfile, "o", "d.json", "输出json文件")
	flag.Parse()

	if len(inputfile) == 0 {
		panic("请输入 excel 文件名称")
	}
	f, err := excelize.OpenFile(inputfile)
	if err != nil {
		fmt.Println(err)
		return
	}

	rows, err := f.GetRows("Sheet1")
	if err != nil {
		fmt.Println("111", err)
		return
	}

	var jsonResult []map[string]string
	keys := make(map[int]string)

	first := true
	var firstColumns int
	for _, row := range rows {
		//fmt.Println("rowIndex:", rowIndex, row)
		if first {
			first = false
			firstColumns = len(row)
			for i, colCell := range row {
				keys[i] = colCell
			}
			continue
		}

		jsonRow := make(map[string]string)
		for i, colCell := range row {
			if i >= firstColumns {
				break
			}
			key := keys[i]
			jsonRow[key] = colCell
		}
		for i := len(row); i < firstColumns; i++ {
			jsonRow[keys[i]] = ""
		}

		jsonResult = append(jsonResult, jsonRow)
	}

	file, e := os.OpenFile(outputfile, os.O_CREATE|os.O_WRONLY, 0666)
	if e != nil {
		panic(e)
	}

	encoder := json.NewEncoder(file)
	err = encoder.Encode(jsonResult)
	if e != nil {
		panic(e)
	}
	fmt.Println("success")
	// Close the spreadsheet.
	//if err = f.Close(); err != nil {
	//fmt.Println(err)
	//}
}
